// const WebSocket = require('ws');

import { getEquipListApi } from '@/api';

// import WebSocket from 'ws';
let ws = null; //;= new WebSocket('ws://192.168.0.155:30080/statelistening');
let isopen = false;
let lastrequestDevicetime = Date.now();
let deviceObj = [];
let timeoutVal = null;
let reccount = 1;

export const initws = () => {
  // ws = new WebSocket('ws://192.168.0.155:30080/statelistening');
  //   ws = new WebSocket();
  //   ws = new WebSocket('ws://127.0.0.1:8080');
  // ws = new WebSocket('ws://192.168.0.106:8080');
  const hostname = window.location.hostname; // 返回主机名部分
  const port = window.location.port; // 返回端口号
  console.log('hostname', hostname);
  console.log('port', port);
  ws = new WebSocket(`ws://${hostname}/statelistening`);
  console.log('ws', ws);
  if (ws.readyState == 1) {
    console.log('WebSocket连接成功...');
  }

  ws.onopen = () => {
    ws.send('login');
    isopen = true;
  };

  ws.onmessage = (e) => {
    console.log('received:', e.data, reccount++);
    // let stringdata = e.data.toString('utf8');
    if (e.data !== 'HeartBeat') {
      FucServerDeviceInfoChanged();
    }
  };

  ws.onclose = () => {
    console.log('ws close');
    isopen = false;
    ws = null;
    setTimeout(function () {
      initws();
    }, 3000);
  };
  setInterval(function ping() {
    if (isopen) {
      ws.send('heartbeat');
    }
  }, 3000);
};

export const FucServerDeviceInfoChanged = () => {
  let now = Date.now();
  if (now - lastrequestDevicetime > 500) {
    lastrequestDevicetime = now;
  } else {
    clearTimeout(timeoutVal);
    timeoutVal = setTimeout(function () {
      FucServerDeviceInfoChanged();
    }, 200);
  }
};

initws();
